﻿package org.leles.ui
{
	import caurina.transitions.Tweener;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	/**
	 * ...
	 * @author Bruno leles
	 */
	public class SimplestScrollbar extends MovieClip
	{
		public var track:MovieClip;
		public var tracker:MovieClip;
		public var trackerAnchor:Point;
		
		protected var _scroll:Number;
		protected var e_scroll:Event;
		protected var draging:Boolean;
		
		public function SimplestScrollbar() 
		{
			super();
			e_scroll = new Event( "scroll" );
			draging = false;
			_scroll = 0;
			if ( stage ) init();
			else addEventListener( Event.ADDED_TO_STAGE, init );
		}
		public function init(e:Event = null):void 
		{
			trackerAnchor = new Point(0,0);
			
			tracker.addEventListener( MouseEvent.MOUSE_DOWN, _tracker_mouse );
		}
		
		private function _tracker_mouse(e:MouseEvent):void 
		{
			switch (e.type) 
			{
				case MouseEvent.MOUSE_DOWN:
					trackerAnchor.x = tracker.mouseX;
					trackerAnchor.y = tracker.mouseY;
					stage.addEventListener( MouseEvent.MOUSE_UP, _tracker_mouse );
					stage.addEventListener( MouseEvent.MOUSE_MOVE, _tracker_mouse );
					draging = true;
					break;
				case MouseEvent.MOUSE_UP:
					stage.removeEventListener( MouseEvent.MOUSE_UP, _tracker_mouse );
					stage.removeEventListener( MouseEvent.MOUSE_MOVE, _tracker_mouse );
					draging =false
					break;
				case MouseEvent.MOUSE_MOVE:
					var yi:Number = Math.min( track.height - tracker.height, Math.max( 0, mouseY - trackerAnchor.y) );
					Tweener.addTween( tracker, { y: yi, time:1, onUpdate:_update } );
					break;
			}
		}
		
		public function _update():void 
		{
			scroll = tracker.y / ( track.height - tracker.height );
		}
		
		public function get scroll():Number { return _scroll; }
		
		public function set scroll(value:Number):void 
		{
			_scroll = value;
			if ( !draging )
			{
				tracker.y = value * (track.height - tracker.height);
			}
			dispatchEvent( e_scroll.clone());
		}
	}
	
}